package com.softaria.windows.widgets;

import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.softaria.windows.config.MenuConfiguration;
import com.softaria.windows.model.ModelUrl;
import com.softaria.windows.model.PerspectiveUrl;
import com.softaria.windows.model.ViewUrl;
import com.softaria.windows.styles.MenuTreeStyles;

/**
 * Left Menu. Contains tree with perspectives and views
 * 
 */
public class MenuTree extends Tree implements MenuTreeStyles {

  public MenuTree(MenuConfiguration conf) {
    getElement().setId(MENU_TREE_ID);
    for (PerspectiveUrl url : conf.getPerspecives()) {

      TreeItem perspectiveItem = addItem(conf.getMenuLabel(url));
      perspectiveItem.setWidth("1px");

      perspectiveItem.setUserObject(url);

      for (ViewUrl view : conf.getViews(url)) {
        TreeItem viewItem = perspectiveItem.addItem(conf.getMenuLabel(view));
        viewItem.setUserObject(view);
      }
    }

  }

  public void highlight(ModelUrl url) {

    for (int i = 0; i < getItemCount(); i++) {
      TreeItem item = getItem(i);

      if (url.equals(item.getUserObject())) {
        setSelectedItemIfNotAlready(item);
        return;
      } else {
        if (doRecursiveHighlight(item, url)) {
          return;
        }
      }
    }

    setSelectedItemIfNotAlready(null);

  }

  private void setSelectedItemIfNotAlready(TreeItem item) {
    TreeItem alreadySelectedItem = getSelectedItem();
    if (alreadySelectedItem == null) {
      if (item != null) {
        setSelectedItem(item, false);
        ensureSelectedItemVisible();
      }
    } else {
      if (!alreadySelectedItem.equals(item)) {
        setSelectedItem(item, false);
        ensureSelectedItemVisible();
      }
    }
  }

  private boolean doRecursiveHighlight(TreeItem item, ModelUrl url) {
    for (int i = 0; i < item.getChildCount(); i++) {
      TreeItem child = item.getChild(i);
      if (url.equals(child.getUserObject())) {
        setSelectedItemIfNotAlready(child);
        return true;
      } else {
        if (doRecursiveHighlight(child, url)) {
          return true;
        }
      }
    }

    return false;
  }

}
